const Utils = require("./utils/util.js");
import fetch from './utils/services'
import webSocket from './utils/socket'

//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    Utils.checkSystemInfo(this);
    console.log('apponLaunch')
  },

  onShow: function() {
    this.logIn()
  },

  logIn: function() {
    wx.login({
      success: res => {
        wx.getUserInfo({
          lang: 'zh_CN',
          withCredentials: true,
          success: info => {
            fetch.post('/user/decodeUserInfo', {
              code: res.code,
              iv: info.iv,
              encryptedData: info.encryptedData,
              type: 1, //获取用户信息
            }).then(data => {
              const param = {
                openId: data.openId,
                unionId: data.unionId,
                type: 3,
                wxName: data.nickName,
                wxPic: data.avatarUrl,
                deviceId: ''
              }
              fetch.post('/weixin/login', param).then(result => {
                wx.setStorageSync('tooken', result.token)
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
                this.globalData.myInfo = result
                if (!webSocket.isConnectSocket) {
                  webSocket.connectSocket({
                    url: webSocket.socketUrl,
                    success: res => {
                      console.log("全局socket连接成功")
                      this.socketAction()
                    },
                    fail: res => {
                      console.log(res)
                    }
                  })
                  wx.onSocketOpen((res) => {
                    console.log('SocketOpen')
                    const param = {
                      fromUserId: result.userCode,
                      objectName: '0',
                      content: '第一次连接',
                    }
                    webSocket.sendSocketMessage({
                      data: JSON.stringify(param),
                      success: res => {
                        // console.log(2, res)
                      },
                      fail: err => {
                        console.log(err)
                      }
                    })
                    webSocket.startHeartBeat();
                  })
                }
              }).catch(err => {
                if (err.code === 123) {
                  wx.reLaunch({
                    url: `/pages/authorized/index?type=userPhone&openId=${data.openId}&unionId=${data.unionId}&wxName=${data.nickName}&wxPic=${data.avatarUrl}`,
                    fail: err => {
                      console.log(err)
                    }
                  })
                } else {
                  wx.showToast({
                    title: err.message || '获取信息失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }).catch(err => {
              wx.showToast({
                title: err.message || '获取信息失败',
                icon: 'none',
                duration: 2000
              })
            })
          },
          fail: err => {
            wx.reLaunch({
              url: `/pages/authorized/index?type=userInfo`,
              fail: err => {
                console.log(err)
              }
            })
          }
        })
      }
    })
  },
  socketAction: function() {
    this.globalData.isInt = true
    wx.onSocketMessage((res) => {
      const data = JSON.parse(res.data)
      // console.log('全局收到消息', data)
      if (data.objectName === 'YH:convers') {
        const info = JSON.parse(data.content)
        const chatInfo = {
          userId: info.friendCode,
          avator: info.friendPic,
          name: info.friendName,
          contactsCode: info.contactsCode,
          converseCode: info.converseCode,
          converseType: info.converseType,
          type: info.type,
        }
        const userInfo = {
          userId: info.friendCode,
          avator: info.friendPic,
          status: 1,
          name: info.friendName
        }
        this.globalData.chatInfo = chatInfo
        this.globalData.userInfo = userInfo
        wx.navigateTo({
          url: '/pages/chat/index?isWaiting=1&contactsCode=' + chatInfo.contactsCode,
          fail: err => {
            console.log(err)
          }
        })
      }

    })
    // wx.onSocketError(function (res) {
    //   console.log('WebSocket连接打开失败，请检查！', res)
    // })
    // wx.onSocketClose(function (res) {
    //   console.log('全局socket关闭')
    // })
  },
  globalData: {
    myInfo: {}, //自己的用户信息
    userInfo: {
    },
    chatInfo: {},
    dialogList: [], //会话列表
    systemInfo: null,
    isInt: false
  }
})